package com.justgame.project.generator.transform.impl;

import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.google.common.base.CaseFormat;
import com.justgame.project.generator.schema.Entity;
import com.justgame.project.generator.schema.Field;
import com.justgame.project.generator.schema.TableSQLCreator;
import com.justgame.project.generator.transform.SQLCreatorTransform;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@DependsOn(value = "mySqlCodeGeneratorImpl")
public class MySQLCreatorTransform implements SQLCreatorTransform {
    @Override
    public TableSQLCreator convert(Entity entity) {
        List<TableSQLCreator.Field> fieldCreators = entity.getFields().stream().map(this::convertField).collect(Collectors.toList());
        List<String> indexNames = entity.getIndexFieldNames();
        return TableSQLCreator.builder(entity.getTableName(),entity.getComment(),"UTF8MB4")
                .fields(fieldCreators)
                .indexNames(indexNames);
    }

    @Override
    public TableSQLCreator.Field convertField(Field field) {
        Assert.isTrue(field.getType() instanceof DbColumnType,String.format("当前数据源：MYSQL，不持支设置 %s 的字段类型",field.getType().getClass().getSimpleName()));
        TableSQLCreator.Field creatorField = new TableSQLCreator.Field();
        creatorField.setName(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,field.getName()));
        creatorField.setComment(field.getComment());
        creatorField.setLength(Optional.ofNullable(field.getLength()).map(BigDecimal::toString).orElse(null));
        creatorField.setIsPrimaryKey(field.getName().equals("id"));
        String type = null;
        switch ((DbColumnType)field.getType()) {
            case STRING: type = "VARCHAR";break;
            case INTEGER: type = "INT";break;
            case LONG:
            case BIG_INTEGER:
                type = "BIGINT";
                break;
            case BOOLEAN: type = "BOOL";break;
            case BIG_DECIMAL:
                type = "DECIMAL";
                creatorField.setLength("18,2");
                break;
            case LOCAL_DATE_TIME: type = "DATETIME";break;
            case CLOB: type = "TEXT";break;
            default:throw new IllegalArgumentException("不支持字段 "+ field.getName()+" 设置的类型值：" +field.getType());
        }
        creatorField.setType(type);
        return creatorField;
    }
}
